package com.lsp.server.user.controller;

import com.lsp.server.common.Apiresponse;
import com.lsp.server.user.domain.po.Org;
import com.lsp.server.user.service.OrgService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @ClassName OrgController
 * @Description TODO
 * @Author Mr Hao
 * @Date 2021/12/6 15:47
 */
@RestController
@RequestMapping("/org")
public class OrgController {

    @Autowired
    private OrgService orgService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增ip
     *
     * @param org
     * @return
     */
    @PostMapping("/addOrg")
    public Apiresponse addOrg(Org org){
        try{
            if (StringUtils.isEmpty(org.getName())){
                return Apiresponse.Error(400,"ip不能为null");
            }
            orgService.addOrg(org);
            return Apiresponse.success("添加成功");
        }catch (IllegalArgumentException e){
            return Apiresponse.Error(500,e.getMessage());
        }
    }

    /**
     * 查询所有ip
     * @return
     */
    @PostMapping("/queryList")
    public Apiresponse queryList(){
        return Apiresponse.success(orgService.queryList());
    }

    /**
     * 禁用，启用ip
     * @param id
     * @param status
     * @return
     */
    @PostMapping("/updateIp")
    public Apiresponse updataIp(Integer id ,Integer status){
        try{
            if (null == id || null == status){
                return Apiresponse.Error(400,"参数错误");
            }
            orgService.updateIp(id,status);
            return Apiresponse.success("");
        }catch (IllegalArgumentException e){
            return Apiresponse.Error(500,e.getMessage());
        }
    }

    @RequestMapping("/reflushOrg")
    public Apiresponse reflushOrg(){
        //清除缓存
        redisTemplate.delete("orgData_elect");
        // 添加缓存
        List<Org> orgs = orgService.queryUseData();
        redisTemplate.opsForValue().set("orgData_elect",orgs);
        return Apiresponse.success("");
    }
}
